package com.example.pdftoofd.utils;

import com.alibaba.fastjson.JSONObject;
import com.example.pdftoofd.entity.HistoryEntity;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class MyFileUtil {
    public static List<HistoryEntity> readLineFile(String filename) {
        List<HistoryEntity> historyEntities = new ArrayList<>();
        try (FileInputStream in = new FileInputStream(filename);
             InputStreamReader inReader = new InputStreamReader(in, "UTF-8");
             BufferedReader bufReader = new BufferedReader(inReader)) {
            String line = null;
            while ((line = bufReader.readLine()) != null) {
                historyEntities.add(JSONObject.parseObject(line, HistoryEntity.class));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return historyEntities;
    }

    public static void writeLineFile(String filename, String content) {
        try (FileOutputStream out = new FileOutputStream(filename, true);
             OutputStreamWriter outWriter = new OutputStreamWriter(out, "UTF-8");
             BufferedWriter bufWrite = new BufferedWriter(outWriter)) {
            bufWrite.write(content + "\r\n");
            bufWrite.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean ifNotExistsAndMkdir(String path) {
        File parentPath = new File(path);
        if (!parentPath.exists()) {
            return parentPath.mkdirs();
        }
        return false;
    }

    public static void ifExistsAndDelete(String path, boolean isDelSelf) {
        File parentPath = new File(path);
        File[] files = parentPath.listFiles();
        for (File file : files) {
            file.delete();
        }
        if (isDelSelf) {
            parentPath.delete();
        }
    }
}
